package com.tzkyzj.tiremanagersystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textfield.TextInputEditText;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.eneities.Tire;
import com.tzkyzj.tiremanagersystem.eneities.TirePhoto;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.network.ApiClient;
import com.tzkyzj.tiremanagersystem.network.ApiResponse;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TireDetailActivity extends AppCompatActivity {

    private static final int REQUEST_ADD_REPAIR = 1001;
    private static final int REQUEST_ADD_SWAP = 1002;

    private Tire tire;
    private List<Photo> generalPhotos = new ArrayList<>();
    private List<Photo> repairPhotos = new ArrayList<>();
    private List<Photo> swapPhotos = new ArrayList<>();
    private List<Photo> scrapPhotos = new ArrayList<>();

    // 视图组件
    private TextView tvUsedMileage, tvUsedDays, tvStatus, tvTotalCost;
    private TextView tvTireNumber, tvTireBrand, tvTireModel, tvAxlePosition;
    private TextView tvVehiclePlateNumber, tvTrailerPlateNumber, tvCurrentPlateNumber;
    private TextView tvInstallDate, tvInstallMileage, tvScrapDate, tvScrapMileage, tvUsedMileageDetail, tvUsedDaysDetail;
    private TextView tvTransportCompany;

    // 费用信息视图
    private TextView tvTirePrice, tvInstallCost, tvRepairCost, tvSwapCost, tvTotalCostDetail;

    // 记录视图
    private TextView tvRepairRecords, tvSwapRecords, tvRepairRecordCount, tvSwapRecordCount;

    private RecyclerView rvGeneralPhotos, rvRepairPhotos, rvSwapPhotos, rvScrapPhotos;
    private PhotoAdapter generalPhotoAdapter, repairPhotoAdapter, swapPhotoAdapter, scrapPhotoAdapter;

    private MaterialButton btnAddRepair, btnAddSwap, btnUsageRecords, btnBackToList;
    private LinearLayout layoutScrap;

    private MaterialCardView cardGeneralPhotos, cardRepairPhotos, cardSwapPhotos,cardScrapPhotos;
    private MaterialCardView cardRepairRecords, cardSwapRecords;

    private TireApiService apiService;
    private DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tire_detail);

        // 获取传递的轮胎数据
        tire = (Tire) getIntent().getSerializableExtra("tire");
        if (tire == null) {
            finish();
            return;
        }

        // 初始化API服务
        apiService = ApiClient.getClient().create(TireApiService.class);

        // 检查认证状态
        checkAuthStatus();

        // 调试 Session 状态
        //ApiClient.debugSession();

        initViews();
        setupToolbar();
        bindData();
        setupRecyclerViews();
        setupClickListeners();
        loadPhotos();
        loadRecords();

        // 立即重新加载数据测试
        reloadTireData();
    }

    private void checkAuthStatus() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String username = prefs.getString("username", null);

        if (username == null) {
            Log.w("TireDetail", "未找到用户信息，可能未登录");
            Toast.makeText(this, "请重新登录", Toast.LENGTH_SHORT).show();
        } else {
            Log.d("TireDetail", "用户已登录: " + username);
        }
    }

    // 修改 reloadTireData 方法，添加 Session 调试
    private void reloadTireData() {
        if (tire == null || tire.getId() == null) {
            return;
        }

        showLoading(true);

        // 调试 Session 状态
        //ApiClient.debugSession();

        Call<ApiResponse<Tire>> call = apiService.getTireDetail(tire.getId());
        call.enqueue(new Callback<ApiResponse<Tire>>() {
            @Override
            public void onResponse(Call<ApiResponse<Tire>> call, Response<ApiResponse<Tire>> response) {
                showLoading(false);
                Log.d("APIDebug", "轮胎详情API响应码: " + response.code());

                if (response.code() == 401) {
                    handleUnauthorizedError();
                    return;
                }

                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Tire updatedTire = response.body().getData();
                    if (updatedTire != null) {
                        tire = updatedTire;
                        bindData();
                        loadRecords();
                        Toast.makeText(TireDetailActivity.this, "数据已更新", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    String errorMsg = "获取更新数据失败";
                    if (response.body() != null) {
                        errorMsg += ": " + response.body().getMessage();
                    }
                    Toast.makeText(TireDetailActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Tire>> call, Throwable t) {
                showLoading(false);
                Toast.makeText(TireDetailActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 修改 handleUnauthorizedError 方法
    private void handleUnauthorizedError() {
        runOnUiThread(() -> {
            Log.e("AuthError", "Session 认证失败，可能需要重新登录");
            Toast.makeText(TireDetailActivity.this, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();

            // 清除用户数据
            SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
            prefs.edit().clear().apply();

            // 清除 ApiClient 实例和 Session
            ApiClient.clearClient();

            // 跳转到登录页面
            Intent intent = new Intent(TireDetailActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }

    private void initViews() {
        // 初始化统计视图
        tvUsedMileage = findViewById(R.id.tvUsedMileage);
        tvUsedDays = findViewById(R.id.tvUsedDays);
        tvStatus = findViewById(R.id.tvStatus);
        tvTotalCost = findViewById(R.id.tvTotalCost);

        // 初始化基本信息视图
        tvTireNumber = findViewById(R.id.tvTireNumber);
        tvTireBrand = findViewById(R.id.tvTireBrand);
        tvTireModel = findViewById(R.id.tvTireModel);
        tvAxlePosition = findViewById(R.id.tvAxlePosition);
        tvVehiclePlateNumber = findViewById(R.id.tvVehiclePlateNumber);
        tvTrailerPlateNumber = findViewById(R.id.tvTrailerPlateNumber);
        tvCurrentPlateNumber = findViewById(R.id.tvCurrentPlateNumber);
        tvTransportCompany = findViewById(R.id.tvTransportCompany);

        // 初始化安装与报废信息视图
        tvInstallDate = findViewById(R.id.tvInstallDate);
        tvInstallMileage = findViewById(R.id.tvInstallMileage);
        tvScrapDate = findViewById(R.id.tvScrapDate);
        tvScrapMileage = findViewById(R.id.tvScrapMileage);
        tvUsedMileageDetail = findViewById(R.id.tvUsedMileageDetail);
        tvUsedDaysDetail = findViewById(R.id.tvUsedDaysDetail);

        // 初始化费用信息视图
        tvTirePrice = findViewById(R.id.tvTirePrice);
        tvInstallCost = findViewById(R.id.tvInstallCost);
        tvRepairCost = findViewById(R.id.tvRepairCost);
        tvSwapCost = findViewById(R.id.tvSwapCost);
        tvTotalCostDetail = findViewById(R.id.tvTotalCostDetail);

        // 初始化记录视图
        tvRepairRecords = findViewById(R.id.tvRepairRecords);
        tvSwapRecords = findViewById(R.id.tvSwapRecords);
        tvRepairRecordCount = findViewById(R.id.tvRepairRecordCount);
        tvSwapRecordCount = findViewById(R.id.tvSwapRecordCount);

        // 初始化RecyclerView
        rvGeneralPhotos = findViewById(R.id.rvGeneralPhotos);
        rvRepairPhotos = findViewById(R.id.rvRepairPhotos);
        rvSwapPhotos = findViewById(R.id.rvSwapPhotos);
        rvScrapPhotos = findViewById(R.id.rvScrapPhotos);

        // 初始化按钮
        btnAddRepair = findViewById(R.id.btnAddRepair);
        btnAddSwap = findViewById(R.id.btnAddSwap);
        btnUsageRecords = findViewById(R.id.btnUsageRecords);
        btnBackToList = findViewById(R.id.btnBackToList);

        // 初始化其他视图
        layoutScrap = findViewById(R.id.layoutScrap);

        // 初始化标记报废按钮
        MaterialButton btnMarkScrap = findViewById(R.id.btnMarkScrap);
        if (btnMarkScrap != null) {
            btnMarkScrap.setOnClickListener(v -> markTireAsScrap());
        }

        // 初始化卡片视图
        cardGeneralPhotos = findViewById(R.id.cardGeneralPhotos);
        cardRepairPhotos = findViewById(R.id.cardRepairPhotos);
        cardSwapPhotos = findViewById(R.id.cardSwapPhotos);
        cardScrapPhotos = findViewById(R.id.cardScrapPhotos);
        cardRepairRecords = findViewById(R.id.cardRepairRecords);
        cardSwapRecords = findViewById(R.id.cardSwapRecords);
    }

    private void markTireAsScrap() {
        TextInputEditText etScrapMileage = findViewById(R.id.etScrapMileage);
        if (etScrapMileage == null || etScrapMileage.getText() == null) {
            Toast.makeText(this, "请输入报废公里数", Toast.LENGTH_SHORT).show();
            return;
        }

        String scrapMileageStr = etScrapMileage.getText().toString().trim();
        if (scrapMileageStr.isEmpty()) {
            Toast.makeText(this, "请输入报废公里数", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            int scrapMileage = Integer.parseInt(scrapMileageStr);
            // 调用API标记轮胎报废
            markTireScrap(scrapMileage);
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的公里数", Toast.LENGTH_SHORT).show();
        }
    }

    private void markTireScrap(int scrapMileage) {
        showLoading(true);

        Call<ApiResponse<Void>> call = apiService.markTireAsScrap(tire.getId(), scrapMileage);
        call.enqueue(new Callback<ApiResponse<Void>>() {
            @Override
            public void onResponse(Call<ApiResponse<Void>> call, Response<ApiResponse<Void>> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(TireDetailActivity.this, "轮胎已标记为报废", Toast.LENGTH_SHORT).show();
                    // 重新加载数据
                    reloadTireData();
                } else {
                    Toast.makeText(TireDetailActivity.this, "标记报废失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Void>> call, Throwable t) {
                showLoading(false);
                Toast.makeText(TireDetailActivity.this, "标记报废失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setTitle("轮胎详情 - " + tire.getTireNumber());
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
        }
    }

    private void bindData() {
        // 绑定使用公里数
        if (tire.getCurrentMileage() != null && tire.getInstallMileage() != null) {
            int usedMileage = tire.getCurrentMileage() - tire.getInstallMileage();
            if (usedMileage > 0) {
                tvUsedMileage.setText(usedMileage + " 公里");
                tvUsedMileageDetail.setText(usedMileage + " 公里");
            } else {
                tvUsedMileage.setText("使用中");
                tvUsedMileageDetail.setText("--");
            }
        } else {
            tvUsedMileage.setText("使用中");
            tvUsedMileageDetail.setText("--");
        }

        // 绑定使用天数
        if (tire.getUsedDays() != null && tire.getUsedDays() > 0) {
            tvUsedDays.setText(tire.getUsedDays() + " 天");
            tvUsedDaysDetail.setText(tire.getUsedDays() + " 天");
        } else {
            tvUsedDays.setText("使用中");
            tvUsedDaysDetail.setText("--");
        }

        // 绑定状态
        if (tire.getScrapDate() == null || tire.getScrapDate().isEmpty()) {
            tvStatus.setText("使用中");
            tvStatus.setTextColor(ContextCompat.getColor(this, android.R.color.holo_green_dark));

            // 使用中时显示操作按钮，隐藏标记报废表单和查询使用记录
            btnAddRepair.setVisibility(View.VISIBLE);
            btnAddSwap.setVisibility(View.VISIBLE);
            btnUsageRecords.setVisibility(View.GONE); // 隐藏查询使用记录
            if (layoutScrap != null) {
                layoutScrap.setVisibility(View.GONE); // 隐藏标记报废表单
            }
        } else {
            tvStatus.setText("已报废");
            tvStatus.setTextColor(ContextCompat.getColor(this, android.R.color.darker_gray));

            // 已报废时隐藏操作按钮，也隐藏标记报废表单和查询使用记录
            btnAddRepair.setVisibility(View.GONE);
            btnAddSwap.setVisibility(View.GONE);
            btnUsageRecords.setVisibility(View.GONE); // 隐藏查询使用记录
            if (layoutScrap != null) {
                layoutScrap.setVisibility(View.GONE); // 已报废时也隐藏
            }
        }

        // 绑定基本信息
        tvTireNumber.setText(tire.getTireNumber());
        tvTireBrand.setText(getSafeString(tire.getTireBrand()));
        tvTireModel.setText(getSafeString(tire.getTireModel()));

        // 绑定轴号和位置 - 修复这里的问题
        String axlePosition = "";
        if (tire.getAxleNumber() != null) {
            axlePosition = tire.getAxleNumber().toString() + "轴";
        }
        if (tire.getTirePosition() != null && !tire.getTirePosition().isEmpty()) {
            axlePosition += " " + tire.getTirePosition();
        }
        tvAxlePosition.setText(axlePosition.isEmpty() ? "--" : axlePosition);

        tvVehiclePlateNumber.setText(getSafeString(tire.getVehiclePlateNumber()));
        tvTrailerPlateNumber.setText(getSafeString(tire.getTrailerPlateNumber()));
        tvCurrentPlateNumber.setText(getSafeString(tire.getCurrentPlateNumber()));
        tvTransportCompany.setText(getSafeString(tire.getTransportCompany()));

        // 绑定安装与报废信息
        tvInstallDate.setText(getSafeString(tire.getInstallDate()));
        tvInstallMileage.setText(getSafeInteger(tire.getInstallMileage()));
        tvScrapDate.setText(getSafeString(tire.getScrapDate()));
        tvScrapMileage.setText(getSafeInteger(tire.getScrapMileage()));

        // 绑定费用信息
        bindCostData();
    }

    private String getSafeString(String value) {
        return value != null && !value.isEmpty() ? value : "--";
    }

    private String getSafeInteger(Integer value) {
        return value != null ? String.valueOf(value) : "--";
    }

    private void bindCostData() {
        // 计算各项费用
        double tirePrice = tire.getTirePrice() != null ? tire.getTirePrice() : 0.0;
        double installCost = tire.getInstallCost() != null ? tire.getInstallCost() : 0.0;
        double repairCost = tire.getRepairCost() != null ? tire.getRepairCost() : 0.0;
        double swapCost = tire.getSwapCost() != null ? tire.getSwapCost() : 0.0;
        double totalCost = tirePrice + installCost + repairCost + swapCost;

        // 设置费用显示
        tvTirePrice.setText(tirePrice > 0 ? "￥" + decimalFormat.format(tirePrice) : "--");
        tvInstallCost.setText(installCost > 0 ? "￥" + decimalFormat.format(installCost) : "--");
        tvRepairCost.setText(repairCost > 0 ? "￥" + decimalFormat.format(repairCost) : "--");
        tvSwapCost.setText(swapCost > 0 ? "￥" + decimalFormat.format(swapCost) : "--");

        tvTotalCost.setText("￥" + decimalFormat.format(totalCost));
        tvTotalCostDetail.setText("￥" + decimalFormat.format(totalCost));
    }

    private void setupRecyclerViews() {
        // 设置普通照片RecyclerView
        generalPhotoAdapter = new PhotoAdapter(generalPhotos, "普通");
        rvGeneralPhotos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvGeneralPhotos.setAdapter(generalPhotoAdapter);

        // 设置修补照片RecyclerView
        repairPhotoAdapter = new PhotoAdapter(repairPhotos, "修补");
        rvRepairPhotos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvRepairPhotos.setAdapter(repairPhotoAdapter);

        // 设置调胎照片RecyclerView
        swapPhotoAdapter = new PhotoAdapter(swapPhotos, "调胎");
        rvSwapPhotos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvSwapPhotos.setAdapter(swapPhotoAdapter);

        // 设置报废照片RecyclerView - 新增
        scrapPhotoAdapter = new PhotoAdapter(scrapPhotos, "报废");
        rvScrapPhotos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvScrapPhotos.setAdapter(scrapPhotoAdapter);
    }

    private void setupClickListeners() {
        btnAddRepair.setOnClickListener(v -> addRepairRecord());
        btnAddSwap.setOnClickListener(v -> addSwapRecord());
        btnUsageRecords.setOnClickListener(v -> showUsageRecords());
        btnBackToList.setOnClickListener(v -> finish());
    }

    private void loadPhotos() {
        // 从服务器加载照片数据
        if (tire.getId() != null) {
            loadAllPhotos();
        }
    }

    private void loadAllPhotos() {
        Log.d("PhotoDebug", "=== 开始加载照片 ===");
        Log.d("PhotoDebug", "轮胎ID: " + tire.getId());

        Call<List<TirePhoto>> call = apiService.getTirePhotos(tire.getId());
        call.enqueue(new Callback<List<TirePhoto>>() {
            @Override
            public void onResponse(Call<List<TirePhoto>> call, Response<List<TirePhoto>> response) {
                Log.d("PhotoDebug", "=== API 响应 ===");
                Log.d("PhotoDebug", "HTTP状态码: " + response.code());
                Log.d("PhotoDebug", "是否成功: " + response.isSuccessful());

                if (response.isSuccessful() && response.body() != null) {
                    List<TirePhoto> photos = response.body();
                    Log.d("PhotoDebug", "成功加载照片数量: " + photos.size());

                    if (!photos.isEmpty()) {
                        processPhotos(photos);
                    } else {
                        Log.d("PhotoDebug", "照片列表为空");
                        hideAllPhotoCards();
                    }
                } else {
                    Log.e("PhotoDebug", "HTTP请求失败或响应体为空");
                    hideAllPhotoCards();
                    Toast.makeText(TireDetailActivity.this, "加载照片失败: 服务器响应错误", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<TirePhoto>> call, Throwable t) {
                Log.e("PhotoDebug", "=== API 请求失败 ===");
                Log.e("PhotoDebug", "失败原因: " + t.getMessage());
                hideAllPhotoCards();
                Toast.makeText(TireDetailActivity.this, "加载照片失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void processPhotos(List<TirePhoto> photos) {
        // 清空现有数据
        generalPhotos.clear();
        repairPhotos.clear();
        swapPhotos.clear();
        scrapPhotos.clear();

        for (TirePhoto photo : photos) {
            String photoUrl = ApiClient.BASE_URL + "api/tires/" + tire.getId() + "/photos/" + photo.getId();
            Log.d("PhotoDebug", "处理照片 - ID: " + photo.getId() + ", 类型: " + photo.getPhotoType() + ", URL: " + photoUrl);

            Photo localPhoto = new Photo(
                    String.valueOf(photo.getId()),
                    photoUrl,
                    photo.getDescription(),
                    photo.getPhotoType()
            );

            if ("GENERAL".equals(photo.getPhotoType())) {
                generalPhotos.add(localPhoto);
            } else if ("REPAIR".equals(photo.getPhotoType())) {
                repairPhotos.add(localPhoto);
            } else if ("SWAP".equals(photo.getPhotoType())) {
                swapPhotos.add(localPhoto);
            } else if ("SCRAP".equals(photo.getPhotoType())) {
                scrapPhotos.add(localPhoto);
            } else {
                Log.w("PhotoLoad", "未知照片类型: " + photo.getPhotoType());
            }
        }

        // 更新UI
        updatePhotoUI();
    }

    private void hideAllPhotoCards() {
        runOnUiThread(() -> {
            cardGeneralPhotos.setVisibility(View.GONE);
            cardRepairPhotos.setVisibility(View.GONE);
            cardSwapPhotos.setVisibility(View.GONE);
            cardScrapPhotos.setVisibility(View.GONE);
        });
    }

    private void updatePhotoUI() {
        // 更新普通照片
        if (generalPhotos.isEmpty()) {
            cardGeneralPhotos.setVisibility(View.GONE);
        } else {
            cardGeneralPhotos.setVisibility(View.VISIBLE);
            generalPhotoAdapter.notifyDataSetChanged();
            updatePhotoCount(generalPhotos.size(), "general");
        }

        // 更新修补照片
        if (repairPhotos.isEmpty()) {
            cardRepairPhotos.setVisibility(View.GONE);
        } else {
            cardRepairPhotos.setVisibility(View.VISIBLE);
            repairPhotoAdapter.notifyDataSetChanged();
            updatePhotoCount(repairPhotos.size(), "repair");
        }

        // 更新调胎照片
        if (swapPhotos.isEmpty()) {
            cardSwapPhotos.setVisibility(View.GONE);
        } else {
            cardSwapPhotos.setVisibility(View.VISIBLE);
            swapPhotoAdapter.notifyDataSetChanged();
            updatePhotoCount(swapPhotos.size(), "swap");
        }

        // 更新报废照片 - 新增
        if (scrapPhotos.isEmpty()) {
            cardScrapPhotos.setVisibility(View.GONE);
        } else {
            cardScrapPhotos.setVisibility(View.VISIBLE);
            scrapPhotoAdapter.notifyDataSetChanged();
            updatePhotoCount(scrapPhotos.size(), "scrap");
        }
    }

    private void loadRecords() {
        // 加载修补记录
        if (tire.getRepairRecords() != null && !tire.getRepairRecords().isEmpty()) {
            tvRepairRecords.setText(tire.getRepairRecords());
            tvRepairRecordCount.setText(countRecords(tire.getRepairRecords()) + " 条记录");
            cardRepairRecords.setVisibility(View.VISIBLE);
        } else {
            cardRepairRecords.setVisibility(View.GONE);
        }

        // 加载调换记录
        if (tire.getSwapRecords() != null && !tire.getSwapRecords().isEmpty()) {
            tvSwapRecords.setText(tire.getSwapRecords());
            tvSwapRecordCount.setText(countRecords(tire.getSwapRecords()) + " 条记录");
            cardSwapRecords.setVisibility(View.VISIBLE);
        } else {
            cardSwapRecords.setVisibility(View.GONE);
        }
    }

    private int countRecords(String records) {
        if (records == null || records.isEmpty()) {
            return 0;
        }
        // 简单的记录计数，按换行符分割
        return records.split("\n").length;
    }

    private void updatePhotoCount(int count, String type) {
        String countText = count + " 张";
        switch (type) {
            case "general":
                TextView tvGeneralPhotoCount = findViewById(R.id.tvGeneralPhotoCount);
                if (tvGeneralPhotoCount != null) {
                    tvGeneralPhotoCount.setText(countText);
                }
                break;
            case "repair":
                TextView tvRepairPhotoCount = findViewById(R.id.tvRepairPhotoCount);
                if (tvRepairPhotoCount != null) {
                    tvRepairPhotoCount.setText(countText);
                }
                break;
            case "swap":
                TextView tvSwapPhotoCount = findViewById(R.id.tvSwapPhotoCount);
                if (tvSwapPhotoCount != null) {
                    tvSwapPhotoCount.setText(countText);
                }
                break;
            case "scrap":
                TextView tvScrapPhotoCount = findViewById(R.id.tvScrapPhotoCount);
                if (tvScrapPhotoCount != null) {
                    tvScrapPhotoCount.setText(countText);
                }
                break;
        }
    }

    private void addRepairRecord() {
        // 检查轮胎是否已报废
        if (tire.getScrapDate() != null && !tire.getScrapDate().isEmpty()) {
            Toast.makeText(this, "该轮胎已报废，无法添加修补记录", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(TireDetailActivity.this, AddRepairActivity.class);
        intent.putExtra("tire", tire);
        startActivityForResult(intent, REQUEST_ADD_REPAIR);
    }

    private void addSwapRecord() {
        // 检查轮胎是否已报废
        if (tire.getScrapDate() != null && !tire.getScrapDate().isEmpty()) {
            Toast.makeText(this, "该轮胎已报废，无法添加调胎记录", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(TireDetailActivity.this, AddSwapActivity.class);
        intent.putExtra("tire", tire);
        startActivityForResult(intent, REQUEST_ADD_SWAP);
    }



    // 修改 onActivityResult 方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ADD_REPAIR) {
            if (resultCode == Activity.RESULT_OK) {
                // 重新加载所有数据
                reloadTireData();
                loadPhotos();
                Toast.makeText(this, "修补记录添加成功", Toast.LENGTH_SHORT).show();
            }
        }
        else if (requestCode == REQUEST_ADD_SWAP && resultCode == Activity.RESULT_OK) {
            reloadTireData();
            loadPhotos();
            Toast.makeText(this, "调胎记录添加成功", Toast.LENGTH_SHORT).show();
        }
    }

    // 添加加载状态显示方法
    private void showLoading(boolean show) {
        ProgressBar progressBar = findViewById(R.id.progressBar);
        if (progressBar != null) {
            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        }

        // 禁用/启用操作按钮
        btnAddRepair.setEnabled(!show);
        btnAddSwap.setEnabled(!show);
        btnUsageRecords.setEnabled(!show);
        btnBackToList.setEnabled(!show);
    }

    private void showUsageRecords() {
        Toast.makeText(this, "查询使用记录: " + tire.getTireNumber(), Toast.LENGTH_SHORT).show();
        // TODO: 实现查询使用记录逻辑
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    // Photo Adapter
    private class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {
        private List<Photo> photos;
        private String photoType;

        public PhotoAdapter(List<Photo> photos, String photoType) {
            this.photos = photos;
            this.photoType = photoType;
        }

        @NonNull
        @Override
        public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false);
            return new PhotoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
            Photo photo = photos.get(position);
            holder.bind(photo, position);
        }

        @Override
        public int getItemCount() {
            return photos.size();
        }

        class PhotoViewHolder extends RecyclerView.ViewHolder {
            private ImageView ivPhoto;
            private TextView tvPhotoCount, tvPhotoType, tvDescription;

            public PhotoViewHolder(@NonNull View itemView) {
                super(itemView);
                ivPhoto = itemView.findViewById(R.id.ivPhoto);
                tvPhotoCount = itemView.findViewById(R.id.tvPhotoCount);
                tvPhotoType = itemView.findViewById(R.id.tvPhotoType);
                tvDescription = itemView.findViewById(R.id.tvDescription);
            }

            public void bind(Photo photo, int position) {
                // 直接加载数据库中的照片，不使用任何占位符
                Glide.with(itemView.getContext())
                        .load(photo.getUrl())
                        .into(ivPhoto);
                // 设置序号
                tvPhotoCount.setText(String.valueOf(position + 1));

                // 设置照片类型
                tvPhotoType.setText(photoType);

                // 设置描述
                if (photo.getDescription() != null && !photo.getDescription().isEmpty()) {
                    tvDescription.setText(photo.getDescription());
                    tvDescription.setVisibility(View.VISIBLE);
                } else {
                    tvDescription.setVisibility(View.GONE);
                }

                // 设置点击事件
                itemView.setOnClickListener(v -> showPhotoDetail(photos, position));
            }
        }
    }

    private void showPhotoDetail(List<Photo> photos, int position) {
        if (photos == null || photos.isEmpty()) {
            Toast.makeText(this, "没有照片可查看", Toast.LENGTH_SHORT).show();
            return;
        }

        // 提取照片URL列表
        ArrayList<String> photoUrls = new ArrayList<>();
        for (Photo photo : photos) {
            photoUrls.add(photo.getUrl());
        }

        Intent intent = new Intent(this, PhotoDetailActivity.class);
        intent.putStringArrayListExtra("photoUrls", photoUrls);
        intent.putExtra("currentPosition", position);
        startActivity(intent);
    }

    // Photo实体类（内部类）
    public static class Photo {
        private String id;
        private String url;
        private String description;
        private String type;

        public Photo(String id, String url, String description, String type) {
            this.id = id;
            this.url = url;
            this.description = description;
            this.type = type;
        }

        public String getId() { return id; }
        public void setId(String id) { this.id = id; }

        public String getUrl() { return url; }
        public void setUrl(String url) { this.url = url; }

        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }

        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
    }
}